<?php
// +----------------------------------------------------------------------
// | 类型转换工具库
// | 参考C#的用法
// +----------------------------------------------------------------------

namespace helper\util;

class Convert
{
    /**
     * 转换为整型(int)
     * @param $var
     * @return int
     */
    public static function toInt($var): int
    {
        return intval($var);// (int) $var
    }

    /**
     * 转换为双精度浮点型(double)
     * @param $var
     * @return float
     */
    public static function toDouble($var): float
    {
        return floatval($var);// (float) $var
    }

    /**
     * 转换为字符串型(string)
     * @param $var
     * @return string
     */
    public static function toString($var): string
    {
        return strval($var);// (string) $var
    }

    /***
     * 对象转数组
     * @param object $object
     * @return array
     */
    public static function toArray(object $object): array
    {
        $array = array();
        foreach ($object as $key => $value) {
            $array[$key] = $value;
        }
        return $array;
    }

    /***
     * 数组转对象
     * @param array $array
     * @return object
     */
    public static function toObject(array $array): object
    {
        return (Object) $array;//json_decode(json_encode($array));
    }

    /**
     * 数组转xml
     * @param array $arr
     * @param bool $isRoot
     * @return string
     */
    public static function toXml(array $arr, bool $isRoot = true): string
    {
        $xml = $isRoot ? '<?xml version="1.0" encoding="utf-8"?>' : '';
        foreach ($arr as $key => $val) {
            if (!is_array($val)) {
                if (is_numeric($val)) {
                    $xml .= "<" . $key . ">" . $val . "</" . $key . ">";
                } else {
                    $xml .= "<" . $key . "><![CDATA[" . $val . "]]></" . $key . ">";
                }
            } else {
                $xml .= "<" . $key . ">";
                $xml .= self::toXml($val, false);
                $xml .= "</" . $key . ">";
            }
        }
        return $xml;
    }
}